#!/usr/evn/bin python
#coding:utf-8

import re
import os
import sys
import types
import inspect

SLICE_SRC = os.path.abspath(os.path.join("slice"))
sys.path.append(SLICE_SRC)

slice_module = __import__("urls", {}, {})
app = getattr(slice_module, "slicehandle")

def main(cond):
    ret = os.popen('rgrep "%s" nutshell --include="*.html|*.pyhtml"' % cond).read()
    ret = ret + os.popen('rgrep "%s" slice --include="*.html|*.pyhtml"' % cond).read()
    matched = [(i.group("fname"), i.group("match")) 
                    for i in re.finditer('\W*(?P<fname>[^:]+)[\w\W]*?"(?P<match>.*%s[^"]+)"'%cond, ret)]
    ls = matched #sorted(list(matched))
    bad = dict([(h, r) for r, h in app._url_mapping])

    for f, i in ls:
        i = re.sub("/[^/]*(currukey|ukey|curr_ukey)[^/]*/", "/user01/", i)
        i = re.sub("%\((?P<ret>[^\)]+)\)\w", "1", i)
        i = re.sub("{{[^}]+}}", "1", i)
        func, urlargs = app.url_to_view(i)
        if func:
            f = None
            if func.func_name == "cached_func":
                for closure_var in func.func_closure:
                    if isinstance(closure_var, types.FunctionType):
                        #print closure_var.func_name
                        f = closure_var
            else:
                #print func.func_name
                f = func

            if f and bad.get(f):
                del bad[f]

            #for r, handler in app._url_mapping:
            #    if handler == f:
            #        
        else:
            print f, i
            raise Exception("Bad Coder")
            #print "No matched function"
    for k, v in bad.iteritems():
        print k.func_name, inspect.getmodule(k)

if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "memcacheKey_201108231626.txt")
